<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class TestDataSeeder extends Seeder
{
    /**
     * 创建模拟数据， 每个用户添加10个学生，每个学生添加100个训练记录.
     *
     * @return void
     */
    public function run()
    {
        //

        $cnum = 10;
        $num = 100;


        $users = DB::table('users')->get();
        foreach ($users as $user) {
            for ($i = 0; $i < $cnum; $i++) {
                $nameLength = rand(2,3);
                $data = [
                    'user_id' => $user->id,
                    'agency_id' => $user->agency_id,
                    'name' => $this->getChar($nameLength),
                    'birthday' => date('Y-m-d', time() - rand(31536000, 157680000)), //1-5岁
                    'sex' => rand(0, 1),
                    'phone' => '131744' . rand(10000, 99999),
                    'address' => '长春市朝阳区'
                ];
                $child_id = DB::table('children')->insertGetId($data);
                $devices = DB::table('devices')->where('agency_id', $user->agency_id)->pluck('id');
                $games = DB::table('games')->select('id', 'grade_id')->get();
                if (count($devices) > 0) {
                    for ($j = 0; $j < $num; $j++) {

                        $usetime = rand(30, 300);
                        $randtime = $usetime + rand(3600, 360000);

                        $start_star = rand(0, 2);
                        $end_star = $start_star + rand(0, 2);
                        $end_star > 3 && $end_star = 3;
                        $result = $end_star == $start_star ? 0 :1;
                        $game = $games->random();
                        $tmp = [
                            'child_id' => $child_id,
                            'game_id' =>$game->id,
                            'grade_id' =>$game->grade_id,
                            'device_id' => $devices->random(),
                            'start_time' => date('Y-m-d H:i:s', time() - $randtime),
                            'end_time' => date('Y-m-d H:i:s', time() - $randtime + $usetime),
                            'use_time' => $usetime,
                            'start_star' => $start_star,
                            'end_star' => $end_star,
                            'result' => $result,
                            'created_at'=>date('Y-m-d H:i:s'),
                            'updated_at'=>date('Y-m-d H:i:s')
                        ];
                        DB::table('histories')->insert($tmp);
                    }
                }

            }
        }
    }
    public function getChar($num)  // $num为生成汉字的数量

    {

        $b = '';

        for ($i=0; $i<$num; $i++) {

            // 使用chr()函数拼接双字节汉字，前一个chr()为高位字节，后一个为低位字节

            $a = chr(mt_rand(0xB0,0xD0)).chr(mt_rand(0xA1, 0xF0));

            // 转码

            $b .= iconv('GB2312', 'UTF-8', $a);

        }

        return $b;

    }
}
